import { Breadcrumb, Button, Card, Input, Modal, Row, Table, Space, Tooltip, Popconfirm, message, Form, notification, Image } from 'antd'
import React, { Component } from 'react'
import {getGoods, deleteGood, getGoodsInfoById, editGoodById} from '../../../api/goods'
import { EditOutlined, DeleteOutlined } from '@ant-design/icons';

export default class GoodsList extends Component {
  state = {
    editGoodModalVisiable: false,
    editGoodID:null,
    editGoodPics:[],
    goodsList: [],
    total:0,
    queryInfo:{
      query:"",
      pagenum:1,
      pagesize:10
    },
    goodsColumns:[
      {
        title:"",
        dataIndex:"",
        align: "center",
        width: "5%",
        render: (text,record,index) => {
          return index + 1;
        }
      },
      {
        title: "商品名称",
        align: "center",
        width: "35%",
        dataIndex: "goods_name"
      },
      {
        title:"商品价格(元)",
        align: "center",
        dataIndex:"goods_price"
      },
      {
        title:"商品重量(kg)",
        align: "center",
        dataIndex:"goods_weight"
      },
      {
        title:"创建时间",
        align: "center",
        dataIndex:"add_time",
        render:(text,record)=>{
          let date = new Date(record.add_time*1000)
          return date.toLocaleDateString()
        }
      },
      {
        title:"操作",
        align: "center",
        render:(text,record) => {
          return (
            <Space>
              <Tooltip title="编辑此商品" placement="top">
                <Button type="primary" onClick={_ => this.showEditGoodModal(record.goods_id)} icon={<EditOutlined/>}></Button>
              </Tooltip>
              <Popconfirm title="确定删除此商品吗？" onConfirm={_ => this.delGood(record.goods_id)}>
                <Button type="danger" icon={<DeleteOutlined/>}></Button>
              </Popconfirm>
            </Space>
          )
        }
      }
    ]
  }
  goToAddGood = () =>{
    this.props.history.push('/admin/addGood')
  }
  getGoodsList = async () => {
    const res = await getGoods(this.state.queryInfo)
    if(res.meta.status !== 200){
      message.error(res.meta.msg);
    }else{
      this.setState({
        goodsList: res.data.goods,
        total:res.data.total
      })
    }
  }
  showEditGoodModal = async (id) => {
    const res = await getGoodsInfoById(id);
    if(res.meta.status !== 200){
      return message.error(res.meta.msg)
    }
    await this.setState({
      editGoodID:id,
      editGoodPics:res.data.pics
    })
    await this.setState({
      editGoodModalVisiable:true,
    })
    this.refs.editGoodFormRef.setFieldsValue({
      "goods_name":res.data.goods_name,
      "goods_weight":res.data.goods_weight,
      "goods_price":res.data.goods_price,
      "goods_number":res.data.goods_number,
      "goods_cat":res.data.goods_cat
    })
  }
  handleCancelEditGood = () => {
    this.setState({
      editGoodModalVisiable:false,
    })
  }
  handleOKEditGood = () => {
    this.refs.editGoodFormRef.submit()
  }
  handleEditGoodFinish = async (values) =>{
    const res = await editGoodById(this.state.editGoodID,values);
    console.log(res)
    if(res.meta.status!==200){
      message.error(res.meta.msg);
    }else{
      message.success(res.meta.msg)
      this.getGoodsList()
    }
    this.handleCancelEditGood()
  }
  handleEditGoodFinishFailed = () =>{
    notification.error("请填写完整表单再提交")
  }
  delGood = async (id) => {
    const res = await deleteGood(id)
    if(res.meta.status !== 200){
      message.error(res.meta.msg)
    }else{
      message.success(res.meta.msg);
      this.getGoodsList()
    }
  }
  onSearch = async (value) => {
    await this.setState({
      queryInfo:{
        query:value,
        pagesize:this.state.queryInfo.pagesize,
        pagenum:this.state.queryInfo.pagenum
      }
    })
    this.getGoodsList();
  }
  paginationChange = async (pagenum,pagesize) => {
    await this.setState({
      queryInfo:{
        query:this.state.queryInfo.query,
        pagesize:pagesize,
        pagenum:pagenum
      }
    })
    this.getGoodsList()
  }
  componentDidMount(){
    this.getGoodsList();
  }
  render() {
    return (
      <div>
        <Card>
          <Breadcrumb>
            <Breadcrumb.Item>首页</Breadcrumb.Item>
            <Breadcrumb.Item>商品管理</Breadcrumb.Item>
            <Breadcrumb.Item>商品列表</Breadcrumb.Item>
          </Breadcrumb>
          <Row style={{marginTop:'10px'}}>
            <Input.Search placeholder="请输入商品名称" onSearch={this.onSearch} style={{ width: 200, marginRight: '10px'}} />
            <Button type="primary" onClick={this.goToAddGood}>添加商品</Button>
          </Row>
          <Table
            style={{marginTop:"10px"}}
            rowKey="goods_id"
            dataSource={this.state.goodsList}
            columns={this.state.goodsColumns}
            bordered
            pagination = {
              {
                pageSize:this.state.queryInfo.pagesize,
                pageSizeOptions:["5","10","15","20"],
                showSizeChanger:true,
                showQuickJumper:true,
                total:this.state.total,
                onChange: this.paginationChange
              }
            }
          >
          </Table>
        </Card>
        <Modal 
          title="编辑商品" 
          visible={this.state.editGoodModalVisiable}
          onOk={this.handleOKEditGood}
          onCancel={this.handleCancelEditGood}
        >
          <Form 
            ref="editGoodFormRef" 
            onFinish={this.handleEditGoodFinish}
            onFinishFailed={this.handleEditGoodFinishFailed}
            labelAlign={{span:4}}
          >
            <Form.Item label="商品图片">
              {this.state.editGoodPics.map(item => {
                return <Image
                  width={50}
                  src={item.pics_mid}
                />
              })}
            </Form.Item>
            <Form.Item label="商品名称" name="goods_name" rules={[{required:true,message:"请填写商品名称"}]}>
              <Input />
            </Form.Item>
            <Form.Item label="商品重量" name="goods_weight" rules={[{required:true,message:"请填写商品重量"}]}>
              <Input type="number"/>
            </Form.Item>
            <Form.Item label="商品数量" name="goods_number" rules={[{required:true,message:"请填写商品数量"}]}>
              <Input type="number"/>
            </Form.Item>
            <Form.Item label="商品价格" name="goods_price" rules={[{required:true,message:"请填写商品价格"}]}>
              <Input type="number"/>
            </Form.Item>
            <Form.Item label="商品类别" name="goods_cat" rules={[{required:true,message:"请填写商品类别"}]}>
              <Input disabled/>
            </Form.Item>
          </Form>
        </Modal>
      </div>
    )
  }
}
